// pages/login/index.js
const {
  showModal,
  showToast
} = require('../../utils/util.js')
const {
  wxCodeLogin
} = require('../../services/api/login.js')
const {
  getWxUserInfo,
  patchUserInfo
} = require('../../services/api/user.js')
let domain = require('../../services/domain.js')
const {
  getAdvImg
} = require('../../services/api/common.js')
const app = getApp()
Page({
  data: {
    isRead: false,
    query: {},
    userInfo: {
      nickName: app.data.$language.l10,
      avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
    },
    logo:'/assets/images/logo.png',
    TinymceData:{

    }
  },
  onShow() {
    app.initPageLang(this)
  },
  onLoad(){
    
    this.loadData()
  },
  loadData() {
    getAdvImg(1).then(res => {
      if (res.code === 0) {
        try {
          this.setData({
            logo:res.info.advertInfoList[0].imgUrl,
            TinymceData:{
              includeSubsets:res.info.advertInfoList[0].includeSubsets,
              advertisingPositionName: res.info.advertInfoList[0].advertisingPositionName,
              content: res.info.advertInfoList[0].content,
            }
          })
        } catch (error) {
          
        }
      }
    })
  },
  toLink() {
    app.toTinymceView(this.data.TinymceData)
  },
  onTip() {
    showModal({
      content: this.data.$language.l11,
      showCancel: false,
      confirmText: this.data.$language.l12,
    })
  },
  onReadHandle() {
    this.setData({
      isRead: this.data.isRead ? false : true
    })
  },
  getPhoneNumberHandle({
    detail
  }) {
    wx.showNavigationBarLoading()
    /*
      res: code|openId
     */
    const loginAction = (res, detail) => {
      console.log(res, detail,"22222222222222");
      const {
        shareId,
        id,
        AntDealerId
      } = this.data.query
      let body = {}
      if (!detail) {
        body = {
          openid: res
        }
      } else {
        if (!detail.iv || !detail.encryptedData) {
          // wx.hideNavigationBarLoading()
          wx.reLaunch({
            url: '/pages/home/index'
          })
          return
        }
        body = {
          code: res.code,
          iv: detail.iv,
          encryptedData: detail.encryptedData,
        }
      }
      if (id || AntDealerId) {
        body.antDealerId = id || AntDealerId
      }
      if (shareId) {
        body.shareAntDealerId = shareId
      }
      wxCodeLogin(body).then(async res => {
        if (res.code === 0) {
          domain.token = res.info.token
          if (res.info.openid) {
            wx.setStorageSync('openid', res.info.openid);
          }
          let _userInfo = {}
          try {
            const userInfoRes = await getWxUserInfo()
            if (userInfoRes.code === 0) {
              _userInfo = userInfoRes.info
            } else {
              throw new Error(this.data.$language.l13,)
            }
          } catch (e) {
            console.log('getWxUserInfo error: ', e)
          }
          let userInfoPathData = {}
          if (!_userInfo.avatar) {
            _userInfo.avatar = this.data.userInfo.avatarUrl
            userInfoPathData.avatar = this.data.userInfo.avatarUrl
          }

          if (!_userInfo.name) {
            _userInfo.name = this.data.userInfo.nickName + _userInfo.phone.slice(7)
            userInfoPathData.name = this.data.userInfo.nickName
          }

          if (Object.keys(userInfoPathData).length > 0) {
            patchUserInfo(userInfoPathData)
          }

          let _phone = res.info.phone
          if (typeof _phone === 'number') {
            _phone += ''
          }
          if (typeof _phone === 'string') {
            _phone = _phone.replace(/^([0-9]{3})[0-9]{4}([0-9]{4})$/, '$1****$2')
          }
          let userInfo = {
            ...app.data.userInfo,
            ...res.info,
            ..._userInfo,
            secretPhone: _phone
          }
          app.data.userInfo = userInfo
          if (res.info.language == 'zh_CN') {
            wx.setStorageSync('language', 'zh');
            app.data.lang = "zh"
          } else if (res.info.language == 'en_US') {
            app.data.lang = "en"
            wx.setStorageSync('language', 'en');
          }
          wx.setStorage({
            key: 'userInfo',
            data: JSON.stringify(userInfo)
          })
          const pages = getCurrentPages()
          if (pages.length > 2) {
            const switchTabs = ['pages/home/index', 'pages/me/index', 'pages/location/index', 'pages/custom/index']
            const {
              route
            } = pages[pages.length - 2]
            if (switchTabs.includes(route)) {
              wx.switchTab({
                url: `/${route}`
              })
            } else {
              wx.navigateBack()
            }
          } else {
            // if (res.info.favoriteSurvey == 1) {
            //   wx.switchTab({
            //     url: '/pages/custom/index'
            //   })
            // } else {
            //   wx.redirectTo({
            //     url: '/subpackages/like/detail/index'
            //   })
            // }
            wx.switchTab({ url: '/pages/custom/index' })
          }
        } else {
          showToast(res.tip)
        }
      }).finally(wx.hideNavigationBarLoading)
    }
    if (typeof detail !== 'string') {
      wx.login({
        success: res => {
          loginAction(res, detail)
        },
        fail: wx.hideNavigationBarLoading
      })
    } else {
      loginAction(detail)
    }
    // wx.switchTab({
    // 	url: '/pages/home/index'
    // })
  },
})